<?php
namespace app\admin\model\User;

use app\admin\validate\User\CustomerValidate;
use app\common\model\User\CustomerCommonModel;
use support\exception\Exception;

class CustomerModel extends CustomerCommonModel
{

    /**
     * 添加方法
     * @param array $data
     * @return bool
     * @throws Exception
     */
    public function addCustomerData(array $data = [])
    {
        //1、验证表单数据
        $validate = new CustomerValidate();
        if(!$validate->scene('add')->check($data)){
            throw new Exception($validate->getError());
        }
        //2、判断用户名是否已存在
        if($this->isExistRecord([ 'username' => $data['username'] ])){
            throw new Exception("用户名已被占用");
        }
        //3、更新密码
        $salt = createRandomString(4 , 4);
        $data['salt'] = $salt;
        $data['password'] = $this->createPassword( $data['password'] , $salt);
        $result = $this->allowField(true)->save($data);
        if($result === false){
            throw new Exception("操作失败");
        }
        return true;
    }

    /**
     * 编辑方法
     * @param int $ids
     * @param array $data
     * @return bool
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function editCustomerData( int $ids , array $data = [])
    {
        $row = $this->find($ids);
        if(empty($row)){
            throw new Exception("记录不存在");
        }
        //1、验证表单数据
        $validate = new CustomerValidate();
        if(!$validate->scene('edit')->check($data)){
            throw new Exception($validate->getError());
        }
        //2、更新密码(空时不需要更新)
        $salt = $row->salt;
        $data['password'] = (!isset($data['password'])|| empty($data['password']) ) ? $row->password : $this->createPassword( $data['password'] , $salt);

        //3、更新数据
        $allowField = ['pid' , 'group_id' , 'password'  , 'name' , 'email' , 'mobile' , 'avatar' , 'birthday' , 'gender' , 'status'];
        $result = $row->allowField($allowField)->save($data);
        if($result === false){
            throw new Exception("操作失败");
        }
        return true;
    }


}